package com.luochq.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class MyNettyServer {
    public static void main(String[] args) {
        // 创建服务器启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(NioServerSocketChannel.class);

        // 创建了一组线程 通过死循环 监控状态 accept r w
        serverBootstrap.group(new NioEventLoopGroup());

        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            /*
                channel 接通 监控 accept rw 处理 通过流水线 用handler 处理
             */
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {

                //ByteBuf 字节 --> 字符
                nioSocketChannel.pipeline().addLast(new StringDecoder());
                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println("msg = " + msg);
                    }
                });
            }
        });

        serverBootstrap.bind(8888);
    }
}
